package cn.easyplatform.studio.dao.transaction;

import cn.easyplatform.studio.dao.DaoUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class JdbcTransaction extends Transaction {

	private static AtomicLong TransIdMaker = new AtomicLong();

	private List<ConnectionInfo> list;

	private long id;

	public JdbcTransaction() {
		list = new ArrayList<ConnectionInfo>();
		id = TransIdMaker.getAndIncrement();
	}

	public void commit() throws SQLException {
		for (ConnectionInfo cInfo : list) {
			// 提交事务
			cInfo.getConn().commit();
			// 恢复旧的事务级别
			if (cInfo.getConn().getTransactionIsolation() != cInfo
					.getOldLevel())
				cInfo.getConn().setTransactionIsolation(cInfo.getOldLevel());
		}
	}

	@Override
	public Connection getConnection(DataSource dataSource) throws SQLException {
		for (ConnectionInfo p : list)
			if (p.getDs() == dataSource)
				return p.getConn();
		Connection conn = dataSource.getConnection();
		if (conn.getAutoCommit())
			conn.setAutoCommit(false);
		list.add(new ConnectionInfo(dataSource, conn, getLevel()));
		return conn;
	}

	public long getId() {
		return id;
	}

	@Override
	public void close() {
		for (ConnectionInfo cInfo : list) {
			try {
				// 试图恢复旧的事务级别
				if (!cInfo.getConn().isClosed()) {
					if (cInfo.getConn().getTransactionIsolation() != cInfo
							.getOldLevel())
						cInfo.getConn().setTransactionIsolation(
								cInfo.getOldLevel());
				}
			} catch (Throwable e) {
			} finally {
				DaoUtils.closeQuietly(cInfo.getConn());
			}
		}
		// 清除数据源记录
		list.clear();
	}

	@Override
	public void rollback() {
		for (ConnectionInfo cInfo : list) {
			try {
				cInfo.getConn().rollback();
			} catch (Throwable e) {
			}
		}
	}

}
